
define(function(require, exports, modules) {
	'use strict';

	require('css!assets/css/home/popup.css');
	require('css!assets/css/home/home.css');
	require('assets/plugins/echarts.js');
	require('assets/plugins/md5.js');

	var popup = require('text!./tpl.popup.html'),
		template = require('text!./tpl.home.html'),
		//ad=require('text!./ad.html'),
		util = require('util');
	var View = Backbone.View.extend({
		el : '#page',
		events : {
			'click .home-menus button': 'menuToggle',
			'click .myheadImg': 'selectPortrait',
			'click button.gamseet' : 'openGameSet',
			'click .gameSetBtn' : 'closeGameSet',
			'click .logoutBtn' : 'logout',
			'click .bgmusic-btn' : 'musicSet',
			'click .sound-btn' : 'soundSet',
			'click #portrait .portrait div': 'chosePortrait',
			'click .home-page .notice em': 'noticeList',
			'click #notice ul li': 'readNotice',
			'click .item-content .name': 'changePassword',
			'click button.chickmail': 'mailList',
			'click button.rule': 'gameRule',
			'click button.shop': 'chickShop',
			'click #chickMarket a':'closeShop',
			'click .noticeBtn':'closeNotice',
			'click .ruleBtn':'closeRule',
			'click .portraitBtn':'closePortrait',
			'click .selectBtn':'confirmPortrait',
			'click .closePasswordBtn':'closePassword',
			'click .confirmChangeBtn':'confirmChange',
			'click .mailBtn':'closeMail',
			'click #alertMsg .only-confirm':'closeMsg',
			'click button.yellowBtn':'toFarm',
			'click button.PY':'toRecords',
			'click button.log':'toLog'
		},
		initialize : function() {
			/*var userStr = util.getCookie('user');
			 var user = $.parseJSON(userStr);
			 if(!user){
			 Backbone.history.navigate('loading',{trigger:true});
			 return;
			 }*/
			this.template = _.template(template);
			this.Popup = _.template(popup);
			this.render();
		},
		render : function() {
			this.$el.html(this.template());
			this.$el.append(this.Popup());
			//this.adSense()
			this.loadUser();
		},
		adSense:function () {
			this.$el.append(ad);
			var h = $('#adsBox .adsContent').height();
			var w = $('#adsBox .adsContent').width();
			$('#adsbygoogleStyle').height(h);
			$('#adsbygoogleStyle').width(w);
		},
		loadUser:function(){
			var userStr = util.getCookie('user');
			var user = $.parseJSON(userStr);
			this.user = user;
			var _this = this;
			this.setting();
			if(user){
				jsonpGet(util.NDNserver+'/refreshHomePage',{userId: user.userId,token: user.token},'refreshHomePage',$.proxy(function(json){
					console.log("refreshHomePage",json)
					if(json.code == '1'){
						var data = json.data;
						data.token = user.token;
						util.setCookie('user',JSON.stringify(data),1); 	//保存user到cookie
						_this.user = data;
					}
					_this.setting();
				},this));
			}else{
				Backbone.history.navigate('loading',{trigger:true});
			}
		},
		setting:function(){
			var user = null,rateList = [0,0,0,0,0,0,0],publicList = [0,0,0,0,0,0,0],dates = [],currRate = 0,publicCurrRate=0;
			var cd = new Date();
			for(var i = 6; i >= 0; i--){
				cd.setDate(cd.getDate() - 1);
				dates[i] = cd.getMonth()+1 + '.' + cd.getDate();
			}
			if(this.user){
				user = this.user;
				$('.userBox .name').text(user.loginName ? user.loginName : '');
				$('.userBox .myheadImg').css({'background-image': user.userPic && user.userPic.length>0 ? "url('"+user.userPic+"')" : "url('assets/images/home/portrait/portrait-man.png')"});
				$('.notice span').text(user.notice ? user.notice.noticeTitle : '');
				$('.userBox .chickmail').addClass(user.mailStatus == '0' ? 'tips' : '');
				//$('.userBox .clm-l').text(user.totalEgg ? user.totalEgg : 0);
				//$('.userBox .clm-r').text(user.totalChicken ? user.totalChicken : 0);
				//鸡蛋与鸡显示处理
				var totalEgg = user.totalEgg ? user.totalEgg : 0;
				var totalChicken = user.totalChicken ? user.totalChicken : 0;
				if($(window).width()<375){
					$('.userBox .clm').addClass('round');
					if(totalEgg>9999){
						totalEgg = parseFloat(totalEgg/10000).toFixed(1)+'万';
					}else if(totalEgg>99999){
						totalEgg = parseFloat(totalEgg/10000).toFixed(0)+'万';
					}else if(totalEgg > 999){
						totalEgg = parseFloat(totalEgg).toFixed(0);
					}else{
						totalEgg = parseFloat(totalEgg).toFixed(1);
					}
					if(totalChicken>9999){
						totalChicken = parseFloat(totalChicken/10000).toFixed(1)+'万';
					}else if(totalChicken>99999){
						totalChicken = parseFloat(totalChicken/10000).toFixed(0)+'万';
					}else if(totalChicken>999){
						totalChicken = parseFloat(totalChicken).toFixed(0);
					}else{
						totalChicken = parseFloat(totalChicken).toFixed(1);
					}
				}else{
					totalEgg = parseFloat(totalEgg).toFixed(1);
					totalChicken = parseFloat(totalChicken).toFixed(1);
				}
				document.querySelector('.userBox .clm-l').innerText = totalEgg;
				document.querySelector('.userBox .clm-r').innerText = totalChicken;
				if(user.musicFlag == '1'){
					$('audio')[0].play();
				}
				console.log('user',user)
				if(user.personRateList && user.personRateList.length > 0){
					if(user.personRateList.length < 7){
						for(var i in user.personRateList){
							rateList[1*i+7-user.personRateList.length] = user.personRateList[i];
						}
					}else{
						rateList = user.personRateList;
					}
					currRate = user.personRateList[user.personRateList.length -1];
				}
				if(user.publicRateList && user.publicRateList.length > 0){
					if(user.publicRateList.length < 7){
						for(var i in user.publicRateList){
							publicList[1*i+7-user.publicRateList.length] = user.publicRateList[i];
						}
					}else{
						publicList=user.publicRateList;
					}
					publicCurrRate = user.publicRateList[user.publicRateList.length -1];
					
				}
			}
			var myChart = echarts.init(document.getElementById('LineChart'));
	        var option = {
	            grid:{
	                x:16, y:40, x2:16, y2:20,
	                borderWidth:'0',
	                borderColor:'transparent'
	            },
	            axis:{
	                axisLine:{
	                    lineStyle:{
	                        color:'#ffcfba'
	                    }
	                }
	            },
//	                tooltip : {
//	                    trigger: 'axis'
//	                },
//	            calculable : true,
				calculable:false,//控制
	            xAxis : [
	                {
	                    type : 'category',
	                    axisLine:{
	                        lineStyle:{
	                            color:'#ffcfba',
	                            width:3
	                        }
	                    },
	                    axisTick:{
	                        inside:true,
	                        lineStyle:{
	                            color:'#ffcfba',
	                            width:3,
	                        }
	                    },
	                    splitLine:{//间隔线
//	                            show:false,
	                        lineStyle:{
	                            color:'#ffcfba',
//	                                type:'dashed',
	                            type:'dotted'
	                        }
	                    },
	                    boundaryGap : false,
	                    //todo:X轴
	                    //data : ['07.03','07.04','07.05','07.06','07.07','07.08','07.09']
	                    data : dates
	                }
	            ],
	            yAxis : [
	                {
	                    show:false,
	                }
	            ],
	            series : [
	                //线段一
	                {
	                    name:'鸡蛋产量',
	                    type:'line',
	                    smooth:true,//平滑
	                    itemStyle: {
	                        normal: {
	                            label:{//标记
	                                show:true,
	                                textStyle:{
	                                    color:'#785113',
	                                    fontSize:'10',
	                                }
	                            },
	                            lineStyle:{
	                                type:'solid'
	                            },
	                            areaStyle: {
	                                color:'rgba(254,135,80,0.15)',
	                                type: 'default'
	                            }
	                        }
	                    },
	                    //todo：X轴对应数据
	                    //data:[180, 400, 100, 300, 460, 400, 500],
	                    data: rateList,
	                    symbol:'emptyCircle'
	                },
					//线段二
					{
						name:'总产量',
						type:'line',
						smooth:false,//平滑
						itemStyle: {
							normal: {
								label:{//标记
									show:true,
									textStyle:{
										color:'#1C881B',
										fontSize:'10',
									}
								},
								lineStyle:{
									type:'solid'
								},
								areaStyle: {
									color:'rgba(255,0,0,0)',
									type: 'default'
								}
							}
						},
						//todo：X轴对应数据
						data:publicList,
						//data: rateList,
						symbol:'emptyCircle'
					}
	            ]
	        }
	        myChart.setOption(option);
	        $('#LineChart').append('<span class="subtext">最新利率：'+currRate+'%</span>');
			$('#LineChart').append('<span class="publicSubtext">公共利率：'+publicCurrRate+'%</span>');
	        //
	        var section = document.querySelector('.userBox section');
	        function setSection (){
	            section.style.lineHeight = $(section).height()+'px';
	            $('.home-menus').width($('#page').width());
	        };
	        document.querySelector('.bg').onload = function () { setSection ();}
	        window.onresize = function () { setSection ();}
	        $(document).ready(function(){ setSection ();})
		},
		//菜单栏
		menuToggle: function(event){
			$(event.currentTarget).addClass('cur').siblings().removeClass('cur');
		},
		popupSet:function(){
			var w = $('.popup .popfloor').width();
			var fh = $('.popup').height();
			var h = w*875/639;
			$('.popup .popfloor').height(h);
			$('.popup .popfloor').css({top: (fh - h)/2 +'px'});
		},
		//公告列表
		noticeList:function(){
			var _this = this;
			if(this.user){
				var	userId = this.user.userId,
				token = this.user.token;
				if(userId && token){
					jsonpGet(util.NDNserver+'/getNoticeList',{userId: userId,token: token},'getNoticeList',$.proxy(function(json){
						if(json.code == '1'){
							var list = json.data;
							for(var i in list){
								list[i].createTime = new Date(list[i].createTime).format('yyyy.mm.dd');
							}
							var currtpl = _.template(util.loadTpl($('#noticeTpl')));
							_this.$el.append(currtpl({noticeList: list}));
							_this.popupSet();
						}
					},this));
				}
			}else{
				var currtpl = _.template(util.loadTpl($('#noticeTpl')));
				this.$el.append(currtpl({noticeList: []}));
				this.popupSet();
			}
		},
		readNotice:function(e){
			$(e.currentTarget).children('.note-context').children('div').slideToggle(300);
			$(e.currentTarget).siblings('li').children('.note-context').children('div').slideUp(300);
		},
		mailList:function(){
			var _this = this;
			if(this.user){
				var userId = this.user.userId,
					token = this.user.token;
				if(userId && token){
					jsonpGet(util.NDNserver+'/getUserTrasRecord',{userId: userId,token: token,type: '0',currentPage: '1',numPerPage: '50'},'getUserTrasRecord',$.proxy(function(json){
						if(json.code == '1'){
							$('.userBox .chickmail').removeClass('tips');
							if(_this.user.mailStatus == '0'){
								_this.user.mailStatus = '1';
								util.setCookie('user',JSON.stringify(_this.user),1); 	//更新user到cookie
							}
							var data = json.data.recordList;
							var list = new Array();
							for(var i in data){
								var d = data[i],cd = {};
								if(d.senderId == userId){//送出
									if(d.giftType == '1' || d.giftType=='5'){
										cd.text = '送出鸡'+d.giftNum+'只';
										cd.calssName = 'chick';
									}else if(d.giftType == '2'  || d.giftType=='6'){
										cd.text = '送出鸡蛋'+d.giftNum+'只';
										cd.calssName = 'egg';
									}else{
										cd.text = '推荐注册花'+d.giftNum+'只';
										cd.calssName = 'chick';
									}
									cd.time = new Date(d.createTime).format('yyyy.mm.dd');
								}
								if(d.receiveId == userId){//获得
									if(d.giftType == '1' || d.giftType=='5'){
										cd.text = '获得鸡'+d.giftNum+'只';
										cd.calssName = 'chick';
									}else if(d.giftType == '2'  || d.giftType=='6'){
										cd.text = '获得鸡蛋'+d.giftNum+'只';
										cd.calssName = 'egg';
									}else{
										cd.text = '首次注册得'+d.giftNum+'只';
										cd.calssName = 'chick';
									}
									cd.time = new Date(d.createTime).format('yyyy.mm.dd');
								}
								list.push(cd);
							}
							var currtpl = _.template(util.loadTpl($('#mailTpl')));
							_this.$el.append(currtpl({mailList: list}));
							_this.popupSet();
						}
					},this));
				}
			}else{
				var currtpl = _.template(util.loadTpl($('#mailTpl')));
				this.$el.append(currtpl({mailList: []}));
				this.popupSet();
			}
		},
		gameRule:function(){
			this.$el.append(util.loadTpl($('#gameRuleTpl')));
			this.popupSet();
		},
		alertSet:function(){
			var fh = $('.alert').height();
			var w = $('.alert .alert-board').width();
			var h = w*481/587;
			$('.alert .alert-board').height(h);
			$('.alert .alert-board').css({top: (fh - h)/2 +'px'});
			
		},
		chickShop:function(){
			this.$el.append(util.loadTpl($('#chickMarketTpl')));
			this.alertSet();
		},
		selectPortrait:function(){
			this.$el.append(util.loadTpl($('#portraitTpl')));
			this.popupSet();
			$('#portrait .list-form').height($('#portrait .list-form').width());
			var style = $('.userBox .myheadImg').attr('style');
			var arr = ['man','woman','dog','chick','man01','girl01','man02','girl02','ji01','gou01'];
			for(var i = 0; i< 10; i++){
				if(style.indexOf(arr[i]) > 0){
					$('#portrait .portrait div:eq('+i+')').addClass('active').siblings('div').removeClass('active');
				}
			}
		},
		chosePortrait:function(e){
			$(e.currentTarget).toggleClass('active').siblings('div').removeClass('active');
		},
		changePassword:function(){
			this.$el.append(util.loadTpl($('#changePasswordTpl')));
			var w = $('#changePassword .password-board').width();
			var fh = $('.alert').height();
			var h = w*509/602;
			$('#changePassword .password-board').height(h);
			$('#changePassword .password-board').css({top: (fh - h)/2 +'px'});
		},
		openGameSet:function(){
			this.$el.append(util.loadTpl($('#gameSetTpl')));
			var w = $('#gameSet .game-set').width();
			var fh = $('.alert').height();
			var h = w*479/602;
			$('#gameSet .game-set').height(h);
			$('#gameSet .game-set').css({top: (fh - h)/2 +'px'});
			if(this.user){
				$('.bgmusic-btn').removeClass('on off').addClass(this.user.musicFlag == '0' ? 'off' : 'on');
				$('.bgmusic-btn .bgmusic-ball').removeClass('on off').addClass(this.user.musicFlag == '0' ? 'off' : 'on');
				$('.sound-btn').removeClass('on off').addClass(this.user.soundFlag == '0' ? 'off' : 'on');
				$('.sound-btn .sound-ball').removeClass('on off').addClass(this.user.soundFlag == '0' ? 'off' : 'on');
			}
		},
		musicSet:function(){
			var status = '0';
			if($('.bgmusic-btn').hasClass('on')){
				$('audio')[0].pause();
				status = '0';
			}else{
				$('audio')[0].play();
				status = '1';
			}
			$('.bgmusic-btn').toggleClass('on off');
			$('.bgmusic-btn .bgmusic-ball').toggleClass('on off');
			this.user.musicFlag = status;
			util.setCookie('user',JSON.stringify(this.user),1); 	//更新user到cookie
			jsonpGet(util.NDNserver+'/updateUser',{userId: this.user.userId,token: this.user.token,type: '1',status: status},'updateUser',function(json){});
		},
		soundSet:function(){
			var status = '0';
			if($('.sound-btn').hasClass('on')){
				//$('audio')[0].pause();
				status = '0';
			}else{
				//$('audio')[0].play();
				status = '1';
			}
			$('.sound-btn').toggleClass('on off');
			$('.sound-btn .sound-ball').toggleClass('on off');
			this.user.soundFlag = status;
			util.setCookie('user',JSON.stringify(this.user),1); 	//更新user到cookie
			jsonpGet(util.NDNserver+'/updateUser',{userId: this.user.userId,token: this.user.token,type: '2',status: status},'updateUser',function(json){});
		},
		closeNotice:function(){
			$('#notice').remove();
		},
		closeMail:function(){
			$('#mail').remove();
		},
		closeRule:function(){
			$('#gameRule').remove();
			$('button.rule').removeClass('cur');
		},
		closeShop:function(){
			$('#chickMarket').remove();
			$('button.shop').removeClass('cur');
		},
		closePortrait:function(){
			$('#portrait').remove();
		},
		confirmPortrait:function(){
			var select = $('#portrait .portrait .active'),
				_this = this;
			if(select.length > 0){
				var i = select.index();
				var url = 'assets/images/home/portrait/';
				switch (i) {
				case 0:
					url += 'portrait-man.png';
					break;
				case 1:
					url += 'portrait-woman.png';
					break;
				case 2:
					url += 'portrait-dog.png';
					break;
				case 3:
					url += 'portrait-chick.png';
					break;
				case 4:
					url += 'portrait-man01.png';
					break;
				case 5:
					url += 'portrait-girl01.png';
					break;
				case 6:
					url += 'portrait-man02.png';
					break;
				case 7:
					url += 'portrait-girl02.png';
					break;
				case 8:
					url += 'portrait-ji01.png';
					break;
				case 9:
					url += 'portrait-gou01.png';
					break;
				}
				$('.myheadImg').css({'background-image':'url('+url+')'});
			}
			if(this.user){
//				console.log({userId: this.user.userId,token: this.user.token,type: '3',status: url})
				jsonpGet(util.NDNserver+'/updateUser',{userId: this.user.userId,token: this.user.token,type: '3',status: url},'updateUser',$.proxy(function(json){
					$('#portrait').remove();
					_this.user.userPic = url;
					util.setCookie('user',JSON.stringify(_this.user),1); 	//更新user到cookie
				},this));
			}else{
				$('#portrait').remove();
			}
		},
		closePassword:function(){
			$('#changePassword').remove();
		},
		confirmChange:function(){
			var _this = this,
				oldPassword = $.trim($('input[name="oldPassword"]').val()),
				newPassword = $.trim($('input[name="newPassword"]').val()),
				confirmPassword = $.trim($('input[name="confirmPassword"]').val());
			if(this.user && oldPassword.length >0 && newPassword.length > 0 && newPassword == confirmPassword){
				jsonpGet(util.NDNserver+'/updatePassword',{userId: this.user.userId,token: this.user.token,oldPassword: hex_md5(oldPassword), newPassword: hex_md5(newPassword)},'updatePassword',$.proxy(function(json){
					if(json.code == '1'){
						$('#changePassword').remove();
					}else if(json.code == '-1'){
						_this.alertMsg();
					}
				},this));
			}else{
				this.alertMsg();
			}
		},
		closeGameSet:function(){
			$('#gameSet').remove();
		},
		logout:function(){
			if(this.user){
				jsonpGet(util.server+'/userLogout',{userId: this.user.userId,token: this.user.token},'userLogout',$.proxy(function(json){
					util.delCookie('user');
					Backbone.history.navigate('login',{trigger:true});
				},this));
			}else{
				Backbone.history.navigate('login',{trigger:true});
			}
			//$('#gameSet').remove();
		},
		alertMsg:function(){
			this.$el.append(util.loadTpl($('#alertMsgTpl')));
			var fh = $('.alert').height();
			var w = $('#alertMsg .msg-board').width();
			var h = w*481/587;
			$('#alertMsg .msg-board').height(h);
			$('#alertMsg .msg-board').css({top: (fh - h)/2 +'px'});
		},
		closeMsg:function(){
			$('#alertMsg').remove();
		},
		toFarm:function(){
			var userCookie = JSON.parse(util.getCookie('user'));
			if(userCookie && userCookie.userStatus == 3){
				commonAlert_oneBtn('您的账号未激活');
				return;
			}
			console.log('userCookie',userCookie)
			loadingShow();
			jsonpGet(
				util.NDNserver+'/enterChickenFarm',
				{
					userId: userCookie.userId,
					token: userCookie.token
				},
				'enterChickenFarm',
				$.proxy(function (res) {
					if(res.code == 1){
						console.log('农场信息');
						console.log(res);
						localStorage.setItem('FarmInitPageData',JSON.stringify(res));
						loadingRemove();
						Backbone.history.navigate('farm',{trigger:true});
					}else if(res.code == -1){
						loadingRemove();
						commonAlert(res.msg);
					}
				},this)
			);
		},
		toRecords:function(){
			var user = $.parseJSON(util.getCookie('user'));
			if(user && user.userStatus == 3){
				commonAlert_oneBtn('您的账号未激活');
				return;
			}
			Backbone.history.navigate('records',{trigger:true});
		},
		toLog:function(){
			var user = $.parseJSON(util.getCookie('user'));
			if(user && user.userStatus == 3){
				commonAlert_oneBtn('您的账号未激活');
				return;
			}
			Backbone.history.navigate('chickensLog',{trigger:true});
		}
	});
	return View;
});